<?php
/**
 * Created by PhpStorm.
 * User: 我想有个家
 * Date: 2020/4/14
 * Time: 11:57
 */

namespace App\Validate;

use Hyperf\Utils\Context;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Validation\ValidationException;
use Psr\Http\Message\ResponseInterface;

class Validate {
    /**
     * @var ValidatorFactoryInterface
     */
    private $validationFactory;

    /**
     * @var RequestInterface
     */
    private $request;

    /**
     * 提示信息
     * @var array
     */
    protected $messages = [];

    public function __construct(RequestInterface $request, ValidatorFactoryInterface $validationFactory) {
        $this->request = $request;
        $this->validationFactory = $validationFactory;
    }

    /**
     * 传入规则验证
     * @param array $rules
     */
    public function check(array $rules) {
        $validator = $this->validationFactory->make($this->request->all(), $rules, $this->messages);
        if ($validator->fails()) {
            // return $validator->errors()->first();
            throw new ValidationException($validator, Context::get(ResponseInterface::class)->withStatus(422));
        }
    }
}
